using imitateMacQQ.WebApi.Configures;
using imitateMacQQ.WebApi.Repository.EFCore.Model;
using imitateMacQQ.WebApi.Repository.Redis;
using imitateMacQQ.WebApi.Repository.Redis.Interface;
using StackExchange.Redis;

namespace imitateMacQQ.WebApi.Repository.EFCore.transform;

public class SqlLinkRedis : ISqlLinkRedis
{
    private readonly IDatabase _redis;
    private readonly INLogHelper _logHelper;

    public SqlLinkRedis(RedisHelper redisHelper, INLogHelper logHelper)
    {
        _logHelper = logHelper;
        _redis = redisHelper.GetDatabase();
        // _db = db;
    }

    // private readonly DataDbContext _db;

    public void ClearRedisData()
    {
        _redis.Execute("FlUSHDb");
    }

    public async Task CacheInfoRedis()
    {
        try
        {
            await using var db = new DataDbContext();
            var data = db.RealTimeInfos;
            await foreach (var item in data)
            {
                var tempValue = RedisProtect.Get(item.User2Account + "inf");
                if (!tempValue.Contains(item.User1Account ?? "NULL") &&
                    !string.IsNullOrEmpty(tempValue))
                {
                    RedisProtect.Set(item.User2Account + "inf",
                        tempValue + "," + item.User1Account);
                }

                if (string.IsNullOrEmpty(tempValue))
                {
                    RedisProtect.Set(item.User2Account + "inf",
                        item.User1Account ?? "NULL");
                }
            }
        }
        catch (Exception ex)
        {
            _logHelper.LogError(ex);
        }
    }
}